package pl.edu.agh.sius.model;

import java.io.Serializable;
import java.net.InetAddress;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.portlet.PortletSession;

import pl.edu.agh.sius.controller.InputFileController;

import com.icesoft.faces.component.inputfile.FileInfo;

public class InputFileData implements Serializable {

	private static final long serialVersionUID = 7726876563468148286L;

	private String host = "localhost";

	@PostConstruct
	public void init() {
		try {
			host = InetAddress.getLocalHost().getHostAddress();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (host == null || "null".equals(host)) {
				host = "localhost";
			}
		}
	}

	// file info attributes
	private FileInfo fileInfo;

	/**
	 * Create a new InputFileDat object.
	 * 
	 * @param fileInfo
	 *            fileInfo object created by the inputFile component for a given
	 *            File object.
	 */
	public InputFileData(FileInfo fileInfo) {
		this.fileInfo = fileInfo;
	}

	public FileInfo getFileInfo() {
		return fileInfo;
	}

	public void setFileInfo(FileInfo fileInfo) {
		this.fileInfo = fileInfo;
	}

	/**
	 * Method to return the file size as a formatted string For example, 4000
	 * bytes would be returned as 4kb
	 * 
	 *@return formatted file size
	 */
	public String getSizeFormatted() {
		long ourLength = fileInfo.getFile().length();

		// Generate formatted label, such as 4kb, instead of just a plain number
		if (ourLength >= InputFileController.MEGABYTE_LENGTH_BYTES) {
			return ourLength / InputFileController.MEGABYTE_LENGTH_BYTES
					+ " MB";
		} else if (ourLength >= InputFileController.KILOBYTE_LENGTH_BYTES) {
			return ourLength / InputFileController.KILOBYTE_LENGTH_BYTES
					+ " KB";
		} else if (ourLength == 0) {
			return "0";
		} else if (ourLength < InputFileController.KILOBYTE_LENGTH_BYTES) {
			return ourLength + " B";
		}

		return Long.toString(ourLength);
	}

	private String fileFormalName;

	public String getFileFormalName() {
		return fileFormalName;
	}

	public void setFileFormalName(String fileFormalName) {
		this.fileFormalName = fileFormalName;
	}

	public String getDownloadURL() {
		StringBuilder sb = new StringBuilder();
		sb.append("http://");
		if (host == null || "localhost".equals(host)) {
			init();
		}
		sb.append(host);
		sb.append(":8080/");
		sb.append(FacesContext.getCurrentInstance().getExternalContext()
				.getRequestContextPath());
		sb.append("/upload/"
				+ ((PortletSession) FacesContext.getCurrentInstance()
						.getExternalContext().getSession(false)).getId() + "/"
				+ fileInfo.getFileName());
		return sb.toString();
	}
}